import React from 'react';
import {
  WhiteSpace,
  List,
  Button,
  Flex,
  Icon,
  Popup,
  WingBlank,
  Toast,
  Picker,
  Modal,
  ActionSheet,
} from 'antd-mobile';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import * as smsService from '../../services/smsService';
import styles from '../../routes/PrecisionPage1_info.css';
import _ from 'lodash';

const modalIframeHeight = window.innerHeight * 0.7 + 'px';

const omit = '...';

const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(window.navigator.userAgent);
let maskProps;
if (isIPhone) {
  // Note: the popup content will not scroll.
  maskProps = {
    onTouchStart: e => e.preventDefault(),
  };
}

class Popup1 extends React.Component {
  state = {
    recommendIndex: [0],
    textEditable: false,
    modal: false,
  }

  wxjs = (url) => {
    const wxShare1 = this.wxShare1 ? this.wxShare1.textContent : omit;
    const imgUrl = this.props.currentUser.profile.avatar || 'http://wx.hy-bang.com/pt/share/img/head.jpg';

    wx.onMenuShareAppMessage({
      title: '育儿小贴士', // 分享标题
      desc: wxShare1, // 分享描述
      link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl, // 分享图标
      success: () => {
        this.props.complete(3);
        this.onClose();
        this.setState({ modal: false });
      },
      cancel: () => {
        Toast.fail('分享失败');
      },
    });
  }

  onClose = (sel) => {
    Popup.hide();
  };

  PickerData = () => {
    const arr = [];
    arr[0] = [];
    this.props.recommend.map((item, index) => {
      arr[0].push({ label: item.goodsRecommend, value: index });
    });
    return arr;
  }

  changePicker = (val) => {
    this.setState({ recommendIndex: val });
  }

  clickEdit = () => {
    this.setState(prevState => (
      {
        textEditable: !prevState.textEditable,
      }
    ), () => {
      if (isIPhone) {
        return;
      }
      if (this.state.textEditable) {
        if (this.parentingTips) {
          this.parentingTips.focus();
        } else if (this.wxShare4) {
          this.wxShare4.focus();
        }
      }
    });
  }

  clickPreview = () => {
    this.setState({ modal: true });
    if (this.state.textEditable) {
      this.setState({ textEditable: false });
    }
  }

  handleSmsSendTypeSelect = (type) => {
    if (this.state.textEditable) {
      this.setState({ textEditable: false });
    }
    const { mobile, vip_tel, card_no, shopId, consume_items, branch } = this.props.vipInfo;
    const { saleManName, shopName, _id, username, phone } = this.props.currentUser;
    //
    let vip_name=this.props.vipInfo.vip_name;
    if (_.isNil(vip_name) || _.isEmpty(vip_name)) {
      vip_name='会员';
    }

    const buyHistory = this.buyHistoyr.textContent;
    let parentingTips = this.parentingTips.textContent;
    if (parentingTips && _.endsWith(parentingTips, '。')) {
      parentingTips = parentingTips.substr(0, parentingTips.length - 1);
    }
    //
    const content = {
      name1: vip_name,
      name2: shopName,
      name3: branch,
      name4: username || saleManName,
      name5: buyHistory,
      text: _.escape(parentingTips),
      cellphone: phone,
    };
    const sp = isIPhone ? '&' : '?';
    //const text = `亲爱的${vip_name}女士/先生，您好！我是${shopName}的育婴师${username || saleManName}, 温馨提示您:${parentingTips}，如有疑问请拨打${phone}`;
    const text = `亲爱的${vip_name}，您好！我是${shopName}的育婴师${username || saleManName}, 温馨提示您:${parentingTips}，如有疑问请拨打${phone}`;
    if (type === 'system') {
      smsService.sendSms(mobile || vip_tel, card_no, _id, username || saleManName, JSON.stringify(content))
        .then((data) => {
          Toast.success('短信发送成功', 2);
          this.props.complete(2);
          this.onClose();
        }).catch((error) => {
          error.response.json().then((d) => {
            Toast.fail(d.message, 2);
            setTimeout(() => {
              const sp = isIPhone ? '&' : '?';
              location.href = `sms:${this.props.vipInfo.mobile || this.props.vipInfo.vip_tel}${sp}body=${_.escape(text)}`;
              this.props.complete(2);
              this.onClose();
            }, 1000);
          });
        });
    }
    if (type === 'phone') {
      const sp = isIPhone ? '&' : '?';
      location.href = `sms:${this.props.vipInfo.mobile || this.props.vipInfo.vip_tel}${sp}body=${_.escape(text)}`;
      this.props.complete(2);
      this.onClose();
    }
  };
  clickShare = () => {
    if (this.props.type == 'smsShare') {
      ActionSheet.showActionSheetWithOptions({
        options: ['系统短信', '手机短信', '取消'],
        message: '请选择短信发送方式',
        cancelButtonIndex: 2,
      },
        (buttonIndex) => {
          if (buttonIndex === -1) return;
          if (buttonIndex === 0) {
            this.handleSmsSendTypeSelect('system');
          } else if (buttonIndex === 1) {
            this.handleSmsSendTypeSelect('phone');
          }
        });
    } else if (this.props.type == 'wxShare') {
      const wxShare1 = this.wxShare1 ? this.wxShare1.textContent : omit;
      const wxShare2 = this.wxShare2 ? this.wxShare2.textContent : omit;
      const wxShare3 = this.wxShare3 ? this.wxShare3.textContent : omit;
      const wxShare4 = this.wxShare4 ? this.wxShare4.textContent : omit;
      const headPortrait = this.props.currentUser.avatar;

      fetch('http://wx.hy-bang.com/consult/share', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          closerRelation: wxShare1,
          parentingKnowledge: wxShare2,
          recommendTalk: wxShare3,
          closeTalk: wxShare4,
          headPortrait,
        }),
      })
        .then(e => e.json()).then((e) => {
          if (e._id) {
            this.wxjs(`http://wx.hy-bang.com/pt/share/index.html?id=${e._id}`);
          /* this.onClose();
           this.setState({modal:false});*/
            this.props.sendWX(true);
          } else {
            Toast.fail('暂时无法分享，请稍等');
          }
        });
    }
  }

  render() {
    const { mobile, vip_tel, card_no, shopId, consume_items, branch } = this.props.vipInfo;
    const { saleManName, shopName, _id, username, phone } = this.props.currentUser;
    const wxShare1 = this.wxShare1 ? this.wxShare1.textContent : omit;
    const wxShare2 = this.wxShare2 ? this.wxShare2.textContent : omit;
    const wxShare3 = this.wxShare3 ? this.wxShare3.textContent : omit;
    const wxShare4 = this.wxShare4 ? this.wxShare4.textContent : omit;
    const headPortrait = this.props.currentUser.avatar;

    let vip_name=this.props.vipInfo.vip_name;
    if (_.isNil(vip_name) || _.isEmpty(vip_name)) {
      vip_name='会员';
    }
    return (
      <div>
        <Modal
          visible={this.state.modal}
          footer={[{
            text: '关闭',
            onPress: () => {
              this.setState({ modal: false });
            },
          },
          {
            text: '微信回访',
            onPress: () => {
              this.clickShare();
            },
          },
          ]}
          style={{ width: '90%' }}
          transparent
        >
          <div style={{ width: '100%', height: modalIframeHeight }}>
            <iframe
              style={{ width: '100%', height: '100%', border: 'none' }}
              src={`http://wx.hy-bang.com/pt/share/index.html?closerRelation=${encodeURIComponent(wxShare1)}&parentingKnowledge=${encodeURIComponent(wxShare2)}&recommendTalk=${encodeURIComponent(wxShare3)}&closeTalk=${encodeURIComponent(wxShare4)}&headPortrait=${headPortrait}`}
            />
          </div>
        </Modal>

        <List
          renderHeader={item => (
            <div style={{ position: 'relative' }}>
              {this.props.type == 'smsShare' ? '短信回访' : '微信回访'}
              <span
                style={{
                  position: 'absolute', right: 3, top: -5,
                }}
                onClick={() => this.onClose('cancel')}
              >
                <Icon type="cross" />
              </span>
            </div>)}
        >
          <div style={{ maxHeight: '400px', overflowY: 'auto' }}>
            <List.Item wrap>
              <div style={{ display: 'flex' }}>
                <div style={{ flex: 1 }}>用户名</div>
                <div style={{ flex: 1, textAlign: 'right' }}>{this.props.vipInfo.vip_name}</div>
              </div>
            </List.Item>
            {
              this.props.type == "smsShare" &&
              <List.Item wrap>
                <div style={{ display: 'flex' }}>
                  <div style={{ flex: 1 }}>手机号码</div>
                  <div
                    style={{
                      flex: 1,
                      textAlign: 'right',
                    }}
                  >{this.props.vipInfo.mobile || this.props.vipInfo.vip_tel}</div>
                </div>
              </List.Item>
            }
            {
              this.props.recommend[this.state.recommendIndex[0]] &&
              <Picker
                title="请选择推荐商品"
                data={this.PickerData()}
                cascade={false}
                value={this.state.recommendIndex}
                onChange={this.changePicker}
              >
                <List.Item arrow="horizontal">推荐商品</List.Item>
              </Picker>
            }
            {
              !this.props.recommend[this.state.recommendIndex[0]] &&
              <Picker
                title="请选择推荐商品"
                data={this.PickerData()}
                cascade={false}
                onChange={this.changePicker}
              >
                <List.Item arrow="horizontal">推荐商品</List.Item>
              </Picker>
            }

            {
              this.props.type == 'smsShare' &&
              <List.Item wrap>
                <div className={styles.scroll}>
                  <span style={{ marginLeft: '2em' }}>
                    亲爱的{vip_name}，您好！我是{shopName}的育婴师{username || saleManName}，温馨提示您：
                  </span>
                  <span
                    className={styles.editStyle} contentEditable={this.state.textEditable} ref={(el) => {
                      this.buyHistoyr = el;
                    }}
                  />
                  <span
                    className={styles.editStyle} contentEditable={this.state.textEditable} ref={(el) => {
                      this.parentingTips = el;
                    }}
                  >
                    {this.props.recommend[this.state.recommendIndex[0]] ? this.props.recommend[this.state.recommendIndex[0]].parentingKnowledge : ''} 产品推荐:{this.props.recommend[this.state.recommendIndex[0]] ? this.props.recommend[this.state.recommendIndex[0]].recommendTalk : ''}
                  </span>
                  <span>
                    如有疑问请拨打 {this.props.currentUser.phone}
                  </span>
                </div>
              </List.Item>
            }

            {
              this.props.type == 'wxShare' &&
              <List.Item wrap>
                <div className={styles.scroll}>
                  <span
                    className={styles.textIndent} contentEditable={this.state.textEditable} ref={(el) => {
                      this.wxShare1 = el;
                    }}
                  >
                 您好！我是【{shopName}】的【{branch}】店铺客户专员【{username || saleManName}】，您上次在我们店买的
                    {_.last(consume_items)},宝宝用得怎么样啦?
                </span>
                  <br />
                  <span
                    className={styles.textIndent} contentEditable={this.state.textEditable} ref={(el) => {
                      this.wxShare2 = el;
                    }}
                  >
                    {this.props.recommend[this.state.recommendIndex[0]] ? this.props.recommend[this.state.recommendIndex[0]].parentingKnowledge : ''}
                  </span>
                  <br />
                  <span
                    className={styles.textIndent} contentEditable={this.state.textEditable} ref={(el) => {
                      this.wxShare3 = el;
                    }}
                  >
                    {this.props.recommend[this.state.recommendIndex[0]] ? this.props.recommend[this.state.recommendIndex[0]].recommendTalk : ''}
                  </span>
                  <br />
                  <span
                    className={styles.textIndent} contentEditable={this.state.textEditable} ref={(el) => {
                      this.wxShare4 = el;
                    }}
                  >
                  我的手机号码是{phone},有任何问题可随时联系我，祝您的宝宝健康成长!
                </span>
                </div>
              </List.Item>
            }

            <WhiteSpace size="lg" />
            <WingBlank>
              <Flex>
                <Flex.Item>
                  <Button
                    type="primary" size="small" onClick={this.clickEdit}
                  >{this.state.textEditable ? '完成' : '编辑'} </Button>
                </Flex.Item>
                {this.props.type == "wxShare" &&
                <Flex.Item>
                  <Button
                    type="primary" size="small" onClick={this.clickPreview}
                  >
                    预览 </Button>
                </Flex.Item>
                }

                {this.props.type == 'smsShare' &&
                <Flex.Item>
                  <Button
                    type="primary" onClick={this.clickShare} size="small"
                  >短信回访</Button>
                </Flex.Item>
                }

              </Flex>
            </WingBlank>

            <WhiteSpace />

          </div>

        </List>
      </div>
    );
  }
}


class VisitFunction extends React.Component {

  complete = (way) => {
    if (this.props.noResult) {
      return;
    }
    setTimeout(() => {
      const { cardNo, taskType, subType } = this.props.location.query;
      /* this.props.history.push({
        pathname: '/p1_result',
        query: { cardNo, taskType, way, subType, salemanId: this.props.vipInfo.saleman_id },
      });*/
      this.props.dispatch(routerRedux.push({
        pathname: '/p1_result',
        query: { cardNo, taskType, way, subType, salemanId: this.props.vipInfo.saleman_id },
      }));
    }, 3000);
  };

  call = () => {
    location.href = `tel:${this.props.vipInfo.mobile || this.props.vipInfo.vip_tel}`;
    this.complete(1);
  };

  onClick2 = () => {
    Popup.show(
      <Popup1
        vipInfo={this.props.vipInfo} recommend={this.props.recommend} currentUser={this.props.currentUser}
        type="smsShare" complete={this.complete}
      />,
      { animationType: 'slide-up', maskProps, maskClosable: false });
  };

  onClick3 = () => {
    const { shopId, vip_name, consume_items } = this.props.vipInfo;
    const { saleManName, shopName } = this.props.currentUser;

    Popup.show(<Popup1
      vipInfo={this.props.vipInfo} recommend={this.props.recommend}
      currentUser={this.props.currentUser} type="wxShare" sendWX={this.props.sendWX}
      complete={this.complete}
    />,
      { animationType: 'slide-up', maskProps, maskClosable: false });
  };
  onSelect = (opt) => {
    this.setState({
      visible: false,
    });
  };
  handleVisibleChange = (visible) => {
    this.setState({
      visible,
    });
  };

  render() {
    const { roles, salemanId } = this.props.currentUser;

    if (salemanId) {
      return (
        <Flex justify="around" style={{ padding: 10, position: 'fixed', left: 0, right: 0, bottom: 0 }}>
          <Flex.Item>
            <Button type="primary" size="small" onClick={this.call} icon={require('../../svg/phone.svg')}>电话</Button>
          </Flex.Item>
          <Flex.Item> <Button
            type="primary" size="small" onClick={this.onClick2}
            icon={require('../../svg/sms.svg')}
          >短信</Button></Flex.Item>
          <Flex.Item> <Button
            type="primary" size="small" onClick={this.onClick3}
            icon={require('../../svg/wechat1.svg')}
          >微信</Button></Flex.Item>
        </Flex>
      );
    }
    return null;
  }
}

export default connect(
  (state, props) => ({
    currentUser: state.auth.currentUser,
    vipInfo: state.task.vipInfo,
    recommend: state.task.recommend,
  }),
)(VisitFunction);
